﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace EdexApiClient
{
    public partial class EdexApiContext
    {
        /// <summary>
        /// Получить перечень товаров
        /// </summary>
        /// <param name="search"></param>
        /// <returns></returns>
        public IEnumerable<WH_ITEMS> GetItems()
        {
            return this.GetItems(String.Empty);
        }

        /// <summary>
        /// Получить перечень товаров
        /// </summary>
        /// <param name="search"></param>
        /// <returns></returns>
        public IEnumerable<WH_ITEMS> GetItems(string search)
        {
            var uri = String.Format("WH_ITEMS/?api_key={0}", this.session.APIKEY);

            if (!String.IsNullOrEmpty(search))
                uri += "&$filter=substringof('" + search + "', ITEM_NAME) eq true or substringof('" + search + "', EXT_KEY) eq true or substringof('" + search + "', ARTICLE) eq true &$top=100";

            uri += "&$orderby=ITEM_NAME";

            return this.GetData<List<WH_ITEMS>>(uri);
        }

        /// <summary>
        /// Получить товар
        /// </summary>
        /// <param name="search"></param>
        /// <returns></returns>
        public WH_ITEMS GetItemDetails(Guid id)
        {
            var uri = String.Format("WH_ITEMS/{0}/?api_key={1}", id.ToString(), this.session.APIKEY);
            return this.GetData<WH_ITEMS>(uri);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ITEM_COMPANY_MAP GetItemMapDetails(string id)
        {
            var uri = String.Format("items_mapping/getbinding/?id={0}&api_key={1}", id, this.session.APIKEY);
            return this.GetData<ITEM_COMPANY_MAP>(uri);
        }

        public void SaveItemMap(Guid ITEM_GUID, Guid SUPPLIER_ITEM_GUID)
        {
            this.Post<ITEM_MAP>(String.Format("items_mapping/?api_key={0}", this.session.APIKEY),
                new ITEM_MAP
                {
                    LEFT_ITEM_GUID = ITEM_GUID,
                    RIGHT_ITEM_GUID = SUPPLIER_ITEM_GUID
                });
        }

        public void AddItem(WH_ITEMS data)
        {
            var uri = String.Format("WH_ITEMS/?api_key={0}", this.session.APIKEY);
            this.Post<WH_ITEMS>(uri, data);
        }

        public void UpdateItem(WH_ITEMS data)
        {
            var uri = String.Format("WH_ITEMS/?api_key={0}", this.session.APIKEY);
            this.Put<WH_ITEMS>(uri, data);
        }

        public void DeleteItem(string id)
        {
            var uri = String.Format("WH_ITEMS/{0}/?api_key={1}", id, this.session.APIKEY);
            this.Delete(uri);
        }
    }
}